﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections.Generic;
using Trig_AMJ_IT_Customforms;
using System.Web.UI.WebControls;
using System.Collections;
using System.Web.UI;

namespace Trig_AMJ_HR_Forms.Layouts.Trig_AMJ_HR_Forms
{
    public partial class Leave_Request_Form : LayoutsPageBase
    {
        SPHelper obj = new SPHelper();
        SP_Group objUG = new SP_Group();

        #region "Properties"

        string CurrentUser = SPContext.Current.Web.CurrentUser.LoginName;

        public static string SiteURL;
        public static string TicketNo;
        public static string MainLstName;
        public static string TaskLstName;
        public static string AttLibName;
        public static string CmntsLstName;
        public static string WorkflowConfigList;
        public static string lstGuid { get; set; }
        public string camlQry { get; set; }
        public static string Mode { get; set; }

        public static string submittedfor { get; set; }

        string ErrorMsgs;

        public static int wfOrder = 0;

        public static string DocumentTypesList { get; set; }
        string WFCurrentOrder = string.Empty;
        string WFTaskType = string.Empty;

        Demand_Voucher_FormClass demandVoucherclass = new Demand_Voucher_FormClass(); // Helper class for this solution
        Trig_WF trigWFClass = new Trig_WF();

        string[] buttonVisibilty = new string[5];

        Label EmpName; Label EmpID; Label Division; Label Department; Label Designation; Label MobNo;

        #endregion

        public Leave_Request_Form()
        {
            SiteURL = SPContext.Current.Site.Url;
            SiteURL = SiteURL + "/sites/forms/";
            MainLstName = "Leave Request Forms";
            TaskLstName = "Leave Request Tasks";
            CmntsLstName = "Leave Request Comments";
            AttLibName = "Attachments";
            WorkflowConfigList = "Workflow Configuration List";
            DocumentTypesList = "DocumentTypes";

        }

        #region "User control manipulation"
        /// <summary>
        /// Get user control controls using find control method 
        /// </summary>
        private void GetUserControls()
        {
            EmpName = userInfo.FindControl("lblEmpName") as Label;
            EmpID = userInfo.FindControl("lblEmpID") as Label;
            Division = userInfo.FindControl("lblDivision") as Label;
            Department = userInfo.FindControl("lblDepartment") as Label;
            Designation = userInfo.FindControl("lblDesignation") as Label;
            MobNo = userInfo.FindControl("lblMobNo") as Label;
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            dtpDate.SelectedDate = DateTime.Today;

            try
            {
                Mode = Request.QueryString["Mode"];
                dtpDate.SelectedDate = DateTime.Today;

                GetUserControls(); // Get Requested By user details

                if (Mode == "New")
                { SPSecurity.RunWithElevatedPrivileges(delegate() { GetEmpInfo(); }); } // Get SubmittedFor user details

                if (!IsPostBack)
                {
                    ImgUser.ImageUrl = demandVoucherclass.GetUserProfilePictureURL(CurrentUser);
                    LblCommentsUserName.Text = CurrentUser;
                    if (Mode == "Edit" || Mode == "View")
                    {
                        FormApprovalLoad(); if (Mode == "View") InvisibleButtons();
                    }
                    else if (Mode == "New")
                    {
                        //SPSecurity.RunWithElevatedPrivileges(delegate() { GetEmpInfo(); });
                        FirstLoadofForm();
                        SetWeodDatas(null);
                    }
                    else
                    {
                        pnlFullForm.Visible = false;
                        pnlAccessDenied.Visible = true;
                        lblAccessDeniedMsg.Visible = true;
                        lblAccessDeniedMsg.Text = "Unable to open the form. Value is missing. Contact administrator";
                    }
                }

            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Leave Request Form" + " :: " + "Parent" + " :: " + "Page_Load";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }


            btnSubmit.Click += new EventHandler(btnSubmit_Click);
            btnReject.Click += new EventHandler(btnReject_Click);
            btnApprove.Click += new EventHandler(btnApprove_Click);

            rtbForward.CheckedChanged += new EventHandler(rtbForward_CheckedChanged);
            rtbSendBack.CheckedChanged += new EventHandler(rtbSendBack_CheckedChanged);
            rtbForwardOthers.CheckedChanged += new EventHandler(rtbForwardOthers_CheckedChanged);

            dtTravelDt.OnValueChangeClientScript = "javascript:ckDates()";
            dtReturnDt.OnValueChangeClientScript = "javascript:ckDates()";
            //dtWorkEOD.OnValueChangeClientScript = "javascript:ckDates()";
            // GetLeaveDays();

            if (wfOrder == 2)
                AssignedNotMe();

        }

        void btnSubmit_Click(object sender, EventArgs e)
        {

            if (Page.IsValid)
            {
                if (Request.QueryString["Mode"] == "Edit")
                {
                    string formID = null;
                    string refNo = Request.QueryString["RefID"];
                    string taskItemID = Request.QueryString["TaskItemID"];
                    string Approver = SPContext.Current.Web.CurrentUser.LoginName;

                    if (GetSendbackStatus())
                    {
                        if (CheckServersideValidation())
                        {
                            SPLongOperation lop = new SPLongOperation(this.Page);
                            lop.LeadingHTML = "<DIV><H4>Leave Request form approval is in progress</H4></DIV>";
                            lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";
                            lop.Begin();
                            obj.ApprovetheForm(SiteURL, MainLstName, TaskLstName, WorkflowConfigList, CmntsLstName, AttLibName, formID, refNo, taskItemID, WFTaskType, Approver,
                                TxtComments.Text, upfile, rtbForwardOthers, rtbSendBack, pplcnt, false, rdBtn.SelectedIndex, txtReqUser.Text);
                            lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");
                        }
                    }
                    else
                    {
                        lblError.Text = "Can't be send back. User is not available";
                    }
                }
                else if (Request.QueryString["Mode"] == "New")
                {
                    SaveFormDetails();
                }
            }
        }

        /// <summary>
        /// Save Form details 
        /// Add Items in Main List
        /// Add Items in Task List
        /// Add Items in Comments List
        /// Add Attachment to Attachment Library
        /// </summary>

        private void SaveFormDetails()
        {
            SPLongOperation lop = new SPLongOperation(this.Page);
            lop.LeadingHTML = "<DIV><H4>Leave Request form submission is in progress...</H4></DIV>";
            lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                obj.AutoNoGeneration(MainLstName, DocumentTypesList, lblLevReqNo, SiteURL);
                TicketNo = Convert.ToString(lblLevReqNo.Text).Trim();
                if (TicketNo.Contains(DateTime.Now.Year.ToString()))
                {
                    lop.Begin();
                    lstGuid = obj.AddLeaveItems(SiteURL, MainLstName, TaskLstName, CmntsLstName, rdBtn.SelectedIndex, AttLibName, upfile, WorkflowConfigList, pplcnt,
                        lblLevReqNo.Text, Convert.ToString(dtpDate.SelectedDate), CurrentUser.ToLower(), EmpID.Text, Division.Text, Designation.Text, MobNo.Text, pplReqUser.CommaSeparatedAccounts.ToLower(), txtReqEmpId.Text,
                        txtReqDivision.Text, txtReqDesignation.Text, txtReqMobileNo.Text, txtNationality.Text, rdBtnLeaveType.SelectedItem.Text, Convert.ToString(dtTravelDt.SelectedDate),
                        Convert.ToString(dtReturnDt.SelectedDate), "", null, rdBtnEligible.SelectedItem.Text, rdBtnAirTkt.SelectedItem.Text, TxtComments.Text,
                        txtDOJ.Text, txtExpYear.Text, txtPassNo.Text, txtPassExpire.Text, txtQatariID.Text, txtQatarIDExpire.Text, txtLeaveOthers.Text, Division, txtReqDepartment.Text);
                    lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");
                }
                else
                {
                    lblError.Text = "Master list details not in Doecument Types"; lblError.ForeColor = System.Drawing.Color.Red;
                }
            });
        }

        void rtbForward_CheckedChanged(object sender, EventArgs e)
        {
            lblError.Text = "";
            lblWFStaticUser.Text = "If you press Submit/Approve the workflow will go to next step";
        }

        void rtbForwardOthers_CheckedChanged(object sender, EventArgs e)
        {
            lblWFStaticUser.Text = "";
            lblError.Text = "";
        }

        void rtbSendBack_CheckedChanged(object sender, EventArgs e)
        {
            lblError.Text = "";
            SPFieldUserValue ofldUser = demandVoucherclass.getSendBackUserfNametoAssignLabelText(SiteURL, TaskLstName, Convert.ToInt16(Request.Params["TaskItemID"]), lblLevReqNo.Text, rtbSendBack, rtbForward, lblError);
            if (ofldUser != null)
            {
                lblWFStaticUser.Text = "Send back to " + ofldUser.User.Name;
                lblSendBacktoUser.Text = ofldUser.User.Name;
            }
        }

        void btnApprove_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                string formID = null;
                string refNo = Request.QueryString["RefID"];
                string taskItemID = Request.QueryString["TaskItemID"];
                string Approver = SPContext.Current.Web.CurrentUser.LoginName;
                if (GetSendbackStatus())
                {
                    if (CheckServersideValidation())
                    {
                        SPLongOperation lop = new SPLongOperation(this.Page);
                        lop.LeadingHTML = "<DIV><H4>Leave Request form approval is in progress</H4></DIV>";
                        lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";
                        lop.Begin();
                        obj.ApprovetheForm(SiteURL, MainLstName, TaskLstName, WorkflowConfigList, CmntsLstName, AttLibName, formID, refNo, taskItemID, WFTaskType, Approver,
                            TxtComments.Text, upfile, rtbForwardOthers, rtbSendBack, pplcnt, false, rdBtn.SelectedIndex, submittedfor);
                        lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");
                    }
                }
                else
                {

                    //lblError.Text = "Can't be send back. User is not available";
                    SPLongOperation lop = new SPLongOperation(this.Page);
                    lop.LeadingHTML = "<DIV><H4>Leave Request form approval is in progress</H4></DIV>";
                    lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";
                    lop.Begin();
                    obj.ApprovetheForm(SiteURL, MainLstName, TaskLstName, WorkflowConfigList, CmntsLstName, AttLibName, formID, refNo, taskItemID, WFTaskType, Approver,
                        TxtComments.Text, upfile, rtbForwardOthers, rtbSendBack, pplcnt, true, rdBtn.SelectedIndex, submittedfor);
                    lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");
                }

                if (wfOrder == 2)
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate() { UpdateWorkeod(refNo); });
                }
            }
        }

        private void UpdateWorkeod(string refNo)
        {
            using (SPSite oSite = new SPSite(SiteURL))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    SPQuery qry = new SPQuery();
                    string camlQry = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + refNo + "</Value></Eq></Where>";
                    qry.Query = camlQry;
                    SPListItem oLstItem = oWeb.Lists.TryGetList(MainLstName).GetItems(qry)[0];
                    SPUser oUser = oWeb.EnsureUser(pplWorkEodTo.CommaSeparatedAccounts);
                    SPFieldUserValue ofldWeod = new SPFieldUserValue(oWeb, oUser.ID, oUser.Name);
                    oLstItem["WorkEndorsedto"] = ofldWeod;
                    oWeb.AllowUnsafeUpdates = true;
                    oLstItem.Update();
                    oWeb.AllowUnsafeUpdates = false;
                }
            }
        }

        void btnReject_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                SPLongOperation lop = new SPLongOperation(this.Page);
                lop.LeadingHTML = "<DIV><H4>Leave Request form rejection in progress</H4></DIV>";
                lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";
                lop.Begin();


                //string formID = null;// Request.QueryString["FormID"];
                string refNo = Request.QueryString["RefID"];
                string TaskItemID = Request.QueryString["TaskItemID"];

                try
                {
                    Label formID = userInfo.FindControl("lblFormID") as Label;
                    SPFieldUserValue userValue = obj.GetSubmittedUser(SiteURL, formID.Text.ToString().Trim(), refNo);
                    trigWFClass.RejectTask(SiteURL, Request.QueryString["TaskItemID"], TaskLstName, MainLstName, Request.QueryString["RefID"]);

                    if (!string.IsNullOrEmpty(upfile.FileName))
                        demandVoucherclass.AddAttachement(SiteURL, AttLibName, refNo, formID.Text, upfile);
                    // Reject user and comments updation
                    string CurrentUser = SPContext.Current.Web.CurrentUser.LoginName;
                    obj.SetCommnets(SiteURL, CmntsLstName, MainLstName, refNo, formID.Text, CurrentUser, TxtComments.Text, 0);


                }
                catch (Exception ex)
                {
                    ErrorMsgs = "Trig_AMJ_HR_Forms :: Leave Request Form" + " :: " + "Parent" + " :: " + "Reject";
                    obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
                }

                lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");

            }
        }


        /// <summary>
        /// check the user availability
        /// </summary>
        /// <returns></returns>

        public bool GetSendbackStatus()
        {
            bool status = true;
            if (rtbSendBack.Checked)
            {
                SPFieldUserValue ofldUser = demandVoucherclass.getSendBackUserfNametoAssignLabelText(SiteURL, TaskLstName, Convert.ToInt16(Request.Params["TaskItemID"]), lblLevReqNo.Text, rtbSendBack, rtbForward, lblError);
                if (ofldUser == null)
                {
                    status = false;
                }
            }
            return status;
        }

        public void rdBtn_SelectedIndexChanged(object sender, EventArgs e)
        {
            ClearUserDetails();
            if (Mode == "New")
            { SPSecurity.RunWithElevatedPrivileges(delegate() { GetEmpInfo(); }); }
            if (rdBtn.SelectedIndex == 0)
                pnlReqEmpInf.Visible = false;
            else
                pnlReqEmpInf.Visible = true;
        }

        public void rdBtnLeaveType_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtLeaveOthers.Text = "";
            if (rdBtnLeaveType.SelectedIndex == 2)
                divLeaveOth.Visible = true;
            else
                divLeaveOth.Visible = false;
        }

        /// <summary>
        /// Check people editor validations
        /// </summary>
        /// <returns></returns>

        public bool CheckServersideValidation()
        {
            bool rval = true;
            if (rtbForwardOthers.Checked)
            {
                if (pplcnt.Accounts.Count > 0)
                {
                    rval = true;
                }
                else
                {
                    rval = false;
                    lblError.Text = "Please enter the user name to forward";
                }
            }
            return rval;
        }

        private void InvisibleButtons()
        {
            btnCntrls.Visible = false;
            pnlView.Visible = true;
            btnSubmit.Visible = false;
            btnApprove.Visible = false;
            btnReject.Visible = false;
            pnlForward.Visible = false;
            pnlCommentArea.Visible = false;
            upAtt.Visible = false;
            btnCancel.Value = "Close";
        }

        /// <summary>
        /// To check whether the Form is in Document Types master list or not.
        /// Also get the document prefix and starting number of the form
        /// Otherwise the user gets Access Denied
        /// </summary>
        public void FirstLoadofForm()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    string[] getDocRefNumber = demandVoucherclass.getRefNum(SiteURL, DocumentTypesList, MainLstName);
                    if (string.IsNullOrEmpty(getDocRefNumber[0]) && string.IsNullOrEmpty(getDocRefNumber[1]))
                    {
                        pnlFullForm.Visible = false;
                        pnlAccessDenied.Visible = true;
                        lblAccessDeniedMsg.Visible = true;
                        lblAccessDeniedMsg.Text = "Access Denied, DocPrefix or Starting Number column value in Document Types Master list is missing. Contact administrator.";
                    }

                });
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Leave Request Form" + " :: " + "Parent" + " :: " + "FirstLoadofForm";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }

        /// <summary>
        /// Get Approver user from task list and check their properties from Workflow Configuration List
        /// Based upon the properties the buttons and radio button should be shown in the screen.
        /// Also bind Submitted details from Master List
        /// </summary>
        public void FormApprovalLoad()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    string TaskItemID = Convert.ToString(Request.QueryString["TaskItemID"]);
                    if (!string.IsNullOrEmpty(TaskItemID))
                    {
                        using (SPSite FrmSite = new SPSite(SiteURL))
                        {
                            using (SPWeb frmweb = FrmSite.OpenWeb())
                            {
                                SPQuery updatecamQ = new SPQuery();
                                updatecamQ.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + TaskItemID + "</Value></Eq></Where>";
                                if (frmweb.Lists.TryGetList(TaskLstName) != null)
                                {
                                    SPListItemCollection oitemcoll = frmweb.Lists.TryGetList(TaskLstName).GetItems(updatecamQ);
                                    if (oitemcoll.Count > 0)
                                    {
                                        SPListItem oitm = oitemcoll[0];
                                        WFCurrentOrder = Convert.ToString(oitm["WFCurrentOrder"]);
                                        WFTaskType = Convert.ToString(oitm["WFTaskType"]);
                                        if (WFTaskType == "Dynamic")
                                        {
                                            pnlForward.Visible = true;
                                        }
                                        RadioButtionListvisibility(frmweb, WFTaskType, false, "", Convert.ToInt32(WFCurrentOrder));
                                    }
                                }
                            }
                        }
                    }
                    ReLoadDetails();
                    //ControlsReadOnly();
                });
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "Parent" + " :: " + "FormApprovalLoad";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }


        /// <summary>
        /// Radio button visibility for dynamic users
        /// </summary>
        /// <param name="tasktype"></param>
        /// <param name="optional"></param>
        /// <param name="OptionalUserName"></param>

        public void RadioButtionListvisibility(SPWeb oweb, string tasktype, bool optional, string OptionalUserName, int WFOrder)
        {
            try
            {
                if (Request.QueryString["Mode"] == "New")
                {
                    pnlForward.Visible = false;
                }
                else if (Request.QueryString["Mode"] == "Edit")
                {
                    if (tasktype == "Static")
                    {
                        pnlForward.Visible = false;
                    }
                    else if (tasktype == "Dynamic")
                    {
                        setRadioButtonVisibilityforDynamicType(WFOrder);
                    }
                    else if (tasktype == "UP Attribute")
                    {
                        pnlForward.Visible = false;
                    }
                    else if (tasktype == "EC (Externally Configured)")
                    {
                        pnlForward.Visible = false;
                    }

                    buttonVisibilty = demandVoucherclass.getForwardbuttonVisibility(SiteURL, WorkflowConfigList, MainLstName, WFOrder);
                    if (buttonVisibilty[3] == "True")
                    {
                        btnApprove.Visible = true;
                        btnReject.Visible = true;
                        btnSubmit.Visible = false;
                    }
                    else
                    {
                        btnApprove.Visible = false;
                        btnReject.Visible = false;
                        btnSubmit.Visible = true;
                    }
                    if (buttonVisibilty[4] == "False")
                    {
                        pnlCommentArea.Visible = false;
                    }

                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "Parent" + " :: " + "RadioButtionListvisibility";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

        }

        /// <summary>
        /// set radion buttons visibilty for the dynamic work flow users
        /// </summary>
        /// <param name="WFOrder"></param>

        public void setRadioButtonVisibilityforDynamicType(int WFOrder)
        {
            try
            {
                buttonVisibilty = demandVoucherclass.getForwardbuttonVisibility(SiteURL, WorkflowConfigList, MainLstName, WFOrder);
                if (buttonVisibilty[0] == "True")
                {
                    rtbSendBack.Visible = true;
                    rtbSendBack.Checked = true;
                }
                else
                {
                    rtbSendBack.Visible = false;
                }
                if (buttonVisibilty[1] == "True")
                {
                    rtbForwardOthers.Visible = true;
                }
                else
                {
                    rtbForwardOthers.Visible = false;
                }

                if (buttonVisibilty[2] == "True")
                {
                    rtbForward.Visible = true;
                }
                else
                {
                    rtbForward.Visible = false;
                }
                if (buttonVisibilty[0] == "False" && buttonVisibilty[1] == "False" && buttonVisibilty[2] == "False")
                {
                    pnlForward.Visible = false;
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "Parent" + " :: " + "setRadioButtonVisibilityforDynamicType";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }


        /// <summary>
        /// Function to bind data after the Form gets submitted.
        /// </summary>
        /// <param name="SiteURL"></param>

        #region "Reload Forms"

        public void ReLoadDetails()
        {
            try
            {
                string RefNo = Convert.ToString(Request.Params["RefID"]);

                camlQry = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + RefNo + "</Value></Eq></Where>";
                SPListItem lstDatas = obj.GetSPListItem(SiteURL, MainLstName, camlQry);
                if (lstDatas != null)
                {
                    lblLevReqNo.Text = Convert.ToString(lstDatas["Reference Number"]);
                    dtpDate.SelectedDate = Convert.ToDateTime(lstDatas["RequestDate"]);

                    Label lblFormID = userInfo.FindControl("lblFormID") as Label;
                    lblFormID.Text = lstDatas.ParentList.ID.ToString();

                    Label lblreferenceNumber = leaveComments.FindControl("lblReferenceNumber") as Label;
                    Label lblSiteUrl = leaveComments.FindControl("lblSiteUrl") as Label;
                    Label lblfrmListName = leaveComments.FindControl("lblfrmListName") as Label;
                    Label lbldocumentypesList = leaveComments.FindControl("lbldocumentTypes") as Label;
                    Label lblCommentsList = leaveComments.FindControl("lblCommentsList") as Label;
                    Label lblTaskList = leaveComments.FindControl("lblTaskList") as Label;

                    lblTaskList.Text = TaskLstName;
                    lblCommentsList.Text = CmntsLstName;
                    lblfrmListName.Text = MainLstName;
                    lbldocumentypesList.Text = DocumentTypesList;
                    lblreferenceNumber.Text = lblLevReqNo.Text;
                    lblSiteUrl.Text = SiteURL;

                    submittedfor = Convert.ToString(lstDatas["SubmittedFor"]);
                    SPFieldUserValue fldUser = new SPFieldUserValue(SPContext.Current.Web, submittedfor);
                    submittedfor = fldUser.LookupValue;

                    if (Convert.ToString(lstDatas["OnBehalfof"]) == "Yes")
                    {
                        pnlSec.Visible = true;
                        pnlSec.Enabled = false;
                        rdBtn.SelectedIndex = 1;
                        pnlReqEmpInf.Visible = true;
                        //trigWFClass.onBehalf = 1;  // Set property value.
                        SetValuestoOnBehalfof(lstDatas);
                    }

                    else
                    {
                        pnlSec.Visible = true;
                        pnlSec.Enabled = false;
                        rdBtn.SelectedIndex = 0;
                    }

                    for (int i = 0; i < rdBtnLeaveType.Items.Count; i++)
                    {
                        if (Convert.ToString(lstDatas["LeaveType"]) == rdBtnLeaveType.Items[i].ToString())
                            rdBtnLeaveType.SelectedIndex = i;
                    }

                    if (Convert.ToString(lstDatas["LeaveType"]) == "Others")
                    {
                        divLeaveOth.Visible = true;
                        txtLeaveOthers.Text = Convert.ToString(lstDatas["LeaveOthers"]);
                    }
                    else
                    {
                        divLeaveOth.Visible = false;
                        txtLeaveOthers.Text = "";
                    }

                    if (Convert.ToString(lstDatas["VacationEligibility"]) == "Yes")
                        rdBtnEligible.SelectedIndex = 0;
                    else rdBtnEligible.SelectedIndex = 1;
                    if (Convert.ToString(lstDatas["AirticketBornebyEmployee"]) == "Yes")
                        rdBtnAirTkt.SelectedIndex = 0;
                    else rdBtnAirTkt.SelectedIndex = 1;

                    string user = Convert.ToString(lstDatas["SubmittedFor"]);

                    //trigWFClass.submittedFor = user;

                    if (!string.IsNullOrEmpty(Convert.ToString(lstDatas["DateofEmployment"])))
                        txtDOJ.Text = Convert.ToDateTime(lstDatas["DateofEmployment"]).ToString("dd/MM/yyyy");

                    txtExpYear.Text = Convert.ToString(lstDatas["YearofExperience"]);
                    txtPassNo.Text = Convert.ToString(lstDatas["PassportNo"]);

                    if (!string.IsNullOrEmpty(Convert.ToString(lstDatas["PassportExpiryOn"])))
                        txtPassExpire.Text = Convert.ToDateTime(lstDatas["PassportExpiryOn"]).ToString("dd/MM/yyyy");
                    txtQatariID.Text = Convert.ToString(lstDatas["QatarID"]);
                    if (!string.IsNullOrEmpty(Convert.ToString(lstDatas["QatarIDExpireOn"])))
                        txtQatarIDExpire.Text = Convert.ToDateTime(lstDatas["QatarIDExpireOn"]).ToString("dd/MM/yyyy");
                    txtNationality.Text = Convert.ToString(lstDatas["Nationality"]);

                    //txtTravelDt.Text = Convert.ToDateTime(lstDatas["TravelDate"]).ToString("dd/MM/yyyy");
                    dtTravelDt.SelectedDate = Convert.ToDateTime(lstDatas["TravelDate"]);
                    dtTravelDt.Enabled = false;
                    //txtTravelDt.Visible = true; dtTravelDt.Visible = false;
                    //txtReturnDt.Text = Convert.ToDateTime(lstDatas["ReturnDate"]).ToString("dd/MM/yyyy");
                    dtReturnDt.SelectedDate = Convert.ToDateTime(lstDatas["ReturnDate"]);
                    dtReturnDt.Enabled = false;
                    //txtReturnDt.Visible = true; dtReturnDt.Visible = false;
                    txtLeaveDays.Text = Convert.ToString(lstDatas["LeaveDays"]);

                    SetWeodDatas(RefNo);

                    if (lstDatas["WorkEndorsedto"] != null)
                    {
                        SPFieldUserValue weodUser = new SPFieldUserValue(SPContext.Current.Web, lstDatas["WorkEndorsedto"].ToString());
                        pplWorkEodTo.Visible = false;
                        pplReqUser.Visible = false;
                        txtWorkEodTo.Visible = true; txtReqUser.ReadOnly = true;
                        txtWorkEodTo.Text = weodUser.LookupValue.ToString();

                    }

                    LeaveHistory(user, gvVacationDetails);


                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "Parent" + " :: " + "ReLoadDetails";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }


        private void AssignedNotMe()
        {

            SPUserCollection userCollection = null;
            if (wfOrder == 2)
            {
                //userCollection = objUG.GetUsersGroups();

                //if (userCollection != null)
                //{
                //    foreach (SPUser user in userCollection)
                //    {
                //        PickerEntity pr = (PickerEntity)pplWorkEodTo.Entities[0];

                //        if (pr.DisplayText != user.Name)
                //        {
                //            pnlAlert.Controls.Add(new LiteralControl("<script language='javascript'>alert('Admin user only allowed!');</script>"));
                //        }
                //    }
                //}
                PickerEntity pkrReqUser = null;
                if (rdBtn.SelectedIndex == 1)
                    pkrReqUser = (PickerEntity)pplReqUser.Entities[0];

                if (pplWorkEodTo.Entities.Count > 0)
                {
                    PickerEntity pkrWoedUser = (PickerEntity)pplWorkEodTo.Entities[0];

                    string loggedUser = SPContext.Current.Web.CurrentUser.Name;

                    if (pkrReqUser != null)
                    {
                        if (pkrReqUser.DisplayText == loggedUser || pkrWoedUser.DisplayText == loggedUser)
                        {
                            pplWorkEodTo.Entities.Clear();
                            pnlAlert.Controls.Add(new LiteralControl("<script language='javascript'>alert('Same user entry not allowed!');</script>"));
                        }
                    }

                    else // (pkrReqUser.DisplayText == loggedUser || pkrWoedUser.DisplayText == loggedUser)
                    {
                        if (pkrWoedUser.DisplayText == loggedUser)
                        {
                            pplWorkEodTo.Entities.Clear();
                            pnlAlert.Controls.Add(new LiteralControl("<script language='javascript'>alert('Same user entry or user have request for leave not allowed!');</script>"));
                        }
                    }
                }
            }
        }


        private void SetWeodDatas(string RefNo)
        {

            if (RefNo != null)
            {
                wfOrder = obj.GetCurrentWFOrder(SiteURL, TaskLstName, RefNo);
                if (wfOrder == 2)
                {
                    hdnWfOrder.Value = "Supervisor";
                    tdWodlbl.Visible = true;
                    tdWodText.Visible = true;
                }
                else if (wfOrder > 2)
                {
                    hdnWfOrder.Value = "others";
                    tdWodlbl.Visible = true;
                    tdWodText.Visible = true;
                }
                else if (Mode == "View")
                {
                    hdnWfOrder.Value = "others";
                    tdWodlbl.Visible = true;
                    tdWodText.Visible = true;
                }
                else
                {
                    hdnWfOrder.Value = "others";
                }

            }
            else
            {
                hdnWfOrder.Value = "others";
            }
        }


        #region "Set Values to OnBehalfof"

        private void SetValuestoOnBehalfof(SPListItem lstDatas)
        {
            SPFieldUserValue user = new SPFieldUserValue(SPContext.Current.Web, lstDatas["SubmittedFor"].ToString());
            //setPeopleEditors(user, pplReqUser);

            pplReqUser.Visible = false;
            txtReqUser.Visible = true; txtReqUser.ReadOnly = true;
            txtReqUser.Text = user.LookupValue.ToString();
            txtReqEmpId.Text = Convert.ToString(lstDatas["EmployeeID"]);
            txtReqDivision.Text = Convert.ToString(lstDatas["Division"]);
            txtReqDepartment.Text = Convert.ToString(lstDatas["Department"]);
            txtReqDesignation.Text = Convert.ToString(lstDatas["Designation"]);
            txtReqMobileNo.Text = Convert.ToString(lstDatas["MobileNo"]);
            txtReqMobileNo.Enabled = false;
        }

        private void setPeopleEditors(SPFieldUserValue user, PeopleEditor ppls)
        {
            ArrayList _arrayList = new ArrayList();
            if (user != null)
            {
                PickerEntity _pickerEntity = new PickerEntity(); // PickerEntitiy use using Microsoft.SharePoint.WebControls
                _pickerEntity.Key = user.LookupValue;
                _pickerEntity.IsResolved = true;
                _arrayList.Add(_pickerEntity);
                ppls.UpdateEntities(_arrayList);
                ppls.Enabled = false;
            }

        }

        #endregion

        #endregion


        #region "On Bahalf of Get Requested Employee Information"

        /// <summary>
        /// Calculate No leave days for leave user
        /// </summary>
        private void GetLeaveDays()
        {
            if (!string.IsNullOrEmpty(Convert.ToString(dtTravelDt.SelectedDate)) && !string.IsNullOrEmpty(Convert.ToString(dtReturnDt.SelectedDate)))
            {
                DateTime DT = DateTime.ParseExact(dtTravelDt.SelectedDate.ToString(), "dd/MM/yyyy", System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);
                double daysUntilNow = DT.Subtract(dtTravelDt.SelectedDate).TotalDays;
                txtLeaveDays.Text = Math.Abs(daysUntilNow).ToString();
            }
        }

        private void GetEmpInfo()
        {
            string user = null;
            if (rdBtn.SelectedIndex == 1 && pplReqUser.Accounts.Count > 0)
            {
                string loginuser = SPContext.Current.Web.CurrentUser.Name;

                PickerEntity pe = (PickerEntity)pplReqUser.Entities[0];

                if (loginuser != pe.DisplayText)
                {
                    string submittedFor = pe.DisplayText;
                    user = submittedFor;
                }
                else
                {
                    user = null;
                    pnlAlert.Controls.Add(new LiteralControl("<script language='javascript'>alert('Same user entry not allowed!');</script>"));
                    pplReqUser.Entities.Clear();
                }
            }
            else if (rdBtn.SelectedIndex == 1 && pplReqUser.Accounts.Count == 0)
            {
                user = null;
            }
            else
            {
                user = CurrentUser;
            }

            if (!string.IsNullOrEmpty(user))
            {
                obj.GetCurrentUserDetails(user, null, txtReqEmpId, txtReqDivision, txtReqDesignation, txtReqMobileNo, txtDOJ,
                      txtPassNo, txtPassExpire, txtQatariID, txtQatarIDExpire, txtNationality);

                if (!string.IsNullOrEmpty(txtDOJ.Text) && txtDOJ.Text != "NA")
                {
                    DateTime DT = DateTime.ParseExact(txtDOJ.Text, "dd/MM/yyyy", System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);
                    double daysUntilNow = DT.Subtract(DateTime.Today).TotalDays;

                    DateTime dt2 = DateTime.Today;
                    //GetExperience(DT, dt2);

                    int days; int months; int years; int Weeks;
                    GetDifference(DT, dt2, out years, out months, out Weeks, out days); // Calculate year of experience for leave user

                    txtExpYear.Text = years.ToString("00") + ":" + months.ToString("00");// +":" + months.ToString("00") + ":" + days.ToString("00");

                    //double yr = daysUntilNow / 365;
                    //txtExpYear.Text = Math.Abs(daysUntilNow).ToString();
                }

                LeaveHistory(user, gvVacationDetails); // Get previous leave records for leave user, to bind in Leave History gridview
            }
        }


        /// <summary>
        /// Calculate work experience of leave user
        /// </summary>
        /// <param name="date1"></param>
        /// <param name="date2"></param>
        /// <param name="Years"></param>
        /// <param name="Months"></param>
        /// <param name="Weeks"></param>
        /// <param name="Days"></param>
        public static void GetDifference(DateTime date1, DateTime date2, out int Years, out int Months, out int Weeks, out int Days)
        {
            //assumes date2 is the bigger date for simplicity

            //years
            TimeSpan diff = date2 - date1;
            Years = diff.Days / 366;
            DateTime workingDate = date1.AddYears(Years);

            while (workingDate.AddYears(1) <= date2)
            {
                workingDate = workingDate.AddYears(1);
                Years++;
            }

            //months
            diff = date2 - workingDate;
            Months = diff.Days / 31;
            workingDate = workingDate.AddMonths(Months);

            while (workingDate.AddMonths(1) <= date2)
            {
                workingDate = workingDate.AddMonths(1);
                Months++;
            }

            //weeks and days
            diff = date2 - workingDate;
            Weeks = diff.Days / 7; //weeks always have 7 days
            Days = diff.Days % 7;


        }

        private void GetExperience(DateTime dt1, DateTime dt2)
        {
            int days = 0;

            if (dt2.Day > dt1.Day)
                days = dt2.Day - dt1.Day;
            else days = dt1.Day - dt2.Day;


            int months = dt2.Month - dt1.Month;
            int years = dt2.Year - dt1.Year;
            if (months < 0)
            {
                months += 12;
                years -= 1;
            }
            if (days < 0)
            {
                dt1.AddYears(years);
                dt1.AddMonths(months);
                days = dt2.Subtract(dt1).Days;
                months -= 1;
            }

            //string.Format("{0:00}", 1); //Prints 01
            //string.Format("{0:00}", 2); //Prints 02

            txtExpYear.Text = years.ToString("00") + ":" + months.ToString("00") + ":" + days.ToString("00");
        }

        private void ClearUserDetails()
        {
            txtReqEmpId.Text = "";
            txtReqDivision.Text = "";
            txtReqDesignation.Text = "";
            txtDOJ.Text = "";
            txtExpYear.Text = "";
            txtPassNo.Text = "";
            txtPassExpire.Text = "";
            txtQatariID.Text = "";
            txtQatarIDExpire.Text = "";
            txtNationality.Text = "";
            txtReqMobileNo.Text = "";
            dtTravelDt.ClearSelection();
            dtReturnDt.ClearSelection();
            txtLeaveDays.Text = "";
            pplWorkEodTo.Entities.Clear();

        }

        /// <summary>
        /// Get leave history details to bind data in gridview
        /// </summary>
        /// <param name="leaveUser"></param>
        /// <param name="gvVacationDetails"></param>
        private void LeaveHistory(string leaveUser, GridView gvVacationDetails)
        {
            string[] str = null;
            if (!string.IsNullOrEmpty(leaveUser))
                str = leaveUser.Split('\\');


            using (SPSite oSite = new SPSite(SiteURL))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    SPQuery qry = new SPQuery();
                    camlQry = "<Where><And><Eq><FieldRef Name=\"SubmittedFor\" /><Value Type=\"User\">" + leaveUser + "</Value></Eq><Eq><FieldRef Name=\"ResumptionStatus\" />" +
                        "<Value Type=\"Text\">Yes</Value></Eq></And></Where><OrderBy><FieldRef Name=\"TravalDate\" Ascending=\"True\" /></OrderBy>";
                    qry.Query = camlQry;
                    SPListItemCollection oItems = oWeb.Lists.TryGetList(MainLstName).GetItems(qry);

                    if (oItems.Count > 0)
                    {
                        pnlgvVacations.Visible = true;
                        trVacationDetails.Visible = false;
                        lblVacationDetails.Text = "";
                        gvVacationDetails.DataSource = oItems.GetDataTable();
                        gvVacationDetails.DataBind();
                        //CkBalanceLeave(leaveUser);
                    }
                    else
                    {
                        hdnBalanceLeave.Value = "";
                        gvVacationDetails.DataSource = null;
                        gvVacationDetails.DataBind();

                        if (rdBtn.SelectedIndex == 1 && string.IsNullOrEmpty(leaveUser))
                        {
                            trVacationDetails.Visible = false;
                            lblVacationDetails.Text = "";
                        }
                        else if (rdBtn.SelectedIndex == 1 && !string.IsNullOrEmpty(leaveUser))
                        {
                            trVacationDetails.Visible = true;
                            lblVacationDetails.Text = "No previous leave records for " + str[1].ToString().ToUpper();
                        }
                        else
                        {
                            trVacationDetails.Visible = true;
                            lblVacationDetails.Text = "No previous leave records for " + str[1].ToString().ToUpper();
                        }
                        if (gvVacationDetails.Rows.Count == 0)
                            pnlgvVacations.Visible = false;
                    }
                    CkBalanceLeave(leaveUser);
                }
            }

        }

        /// <summary>
        /// Get Balance leave for leave user.
        /// </summary>
        /// <param name="leaveUser"></param>
        private void CkBalanceLeave(string leaveUser)
        {
            camlQry = "<Where><Eq><FieldRef Name=\"User\" /><Value Type=\"User\">" + leaveUser + "</Value></Eq></Where>";
            SPListItem oItem = obj.GetSPListItem(SiteURL, "User Leave Master", camlQry);
            if (oItem != null)
            {
                hdnBalanceLeave.Value = Convert.ToString(oItem["BalanceLeave"]);
            }
        }

        #endregion


    }
}
